package top.dj.util;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.dj.entity.FileInfo;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: DengJia
 * @Date: 2021/9/9 9:54
 * @Description:
 */

@Component
public class FastDfsClientUtil {
    @Value("${file.req-host}")
    private String reqHost;
    @Value("${file.req-port}")
    private String reqPort;

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件信息
     */
    public FileInfo uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new NullPointerException("请上传文件");
        }

        String fileType = FilenameUtils.getExtension(file.getOriginalFilename());
        InputStream inputStream = null;
        StorePath storePath;

        try {
            inputStream = file.getInputStream();
            storePath = storageClient.uploadFile(inputStream, file.getSize(), fileType, null);
            return new FileInfo.Builder(storePath.getFullPath())
                    .fileName(file.getOriginalFilename())
                    .fileSize(file.getSize())
                    .fileType(fileType)
                    .filePath(getURL(storePath))
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close(); // 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 文件下载
     */
    public InputStream download(String group, String path) {
        /*return storageClient.downloadFile(group, path, new DownloadCallback<InputStream>() {
            @Override
            public InputStream recv(InputStream ins) throws IOException {
                return ins;
            }
        });*/
        return storageClient.downloadFile(group, path, ins -> {
            return ins; // 将ins返回给外面的InputStream再返回
        });
    }

    /**
     * 文件删除
     *
     * @param filePath group + path
     */
    public void delFile(String filePath) {
        storageClient.deleteFile(filePath);
    }

    // 获取完整路径
    public String getURL(StorePath storePath) {
        return "http://" + reqHost + ":" + reqPort + "/" + storePath.getFullPath();
    }
}
